package com.lfs.handler;

import com.alibaba.excel.write.handler.WriteHandler;

import java.util.List;

/**
 * 下拉框实现器
 */
import com.alibaba.excel.write.handler.CellWriteHandler;
import com.alibaba.excel.write.handler.context.CellWriteHandlerContext;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteTableHolder;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddressList;

import java.util.List;

public class DropdownWriteHandler implements CellWriteHandler {

    private final List<String> dropdownOptions;

    public DropdownWriteHandler(List<String> dropdownOptions) {
        this.dropdownOptions = dropdownOptions;
    }

    @Override
    public void afterCellCreate(CellWriteHandlerContext context) {
        // 在单元格创建后，检查是否是目标列（第4列，索引为 3）
        int columnIndex = context.getColumnIndex();
        if (columnIndex == 3) {
            Sheet sheet = context.getWriteSheetHolder().getSheet();
            DataValidationHelper helper = sheet.getDataValidationHelper();
            DataValidationConstraint constraint = helper.createExplicitListConstraint(dropdownOptions.toArray(new String[0]));

            // 设置下拉框的范围（从第1行到最后一行）
            CellRangeAddressList regions = new CellRangeAddressList(0, Integer.MAX_VALUE, columnIndex, columnIndex);
            DataValidation validation = helper.createValidation(constraint, regions);

            // 禁用错误提示
            validation.setSuppressDropDownArrow(true);
            validation.setShowErrorBox(false);

            // 添加到工作表
            sheet.addValidationData(validation);
        }
    }

    @Override
    public void afterCellDataConverted(CellWriteHandlerContext context) {
        // 空实现
    }

    @Override
    public void afterCellDispose(CellWriteHandlerContext context) {
        // 空实现
    }
}
